
package doc2db.interfaces.action.InsUpd;

import doc2db.DbManager.DbSelects;
import doc2db.Keey;
import doc2db.UserProp;
import doc2db.fileWorker.FileBeginer;
import doc2db.fileWorker.FileWorker;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

/**
 *
 * @author yuriy
 *
 * ┌─────────────────────────────────────────────────┐
 * │ table_schema.table_name                         │
 * ├───────────┬───────────┬─────────────┬───────────┤
 * │column_name│column_name│             │column_name│
 * │ [ name  ] │ [ name  ] │             │ [ name  ] │
 * │ data_type │ data_type │             │ data_type │
 * │ [ type  ] │ [ type  ] │             │ [ type  ] │
 * │           │           │  .  .  .    │           │
 * │   data    │   data    │             │   data    │
 * │ ┌       ┐ │ ┌       ┐ │             │ ┌       ┐ │
 * │ │       │ │ │       │ │             │ │       │ │
 * │ └       ┘ │ └       ┘ │             │ └       ┘ │
 * ├───────────┴───────────┴─────────────┴───────────┤
 * │                                                 │
 * │                                   cancel   ok   │
 * └─────────────────────────────────────────────────┘
 *
 * select  TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE,
 * CHARACTER_MAXIMUM_LENGTH from db_name.information_schema.columns where
 * table_name = 'table_name';
 *
 *  extends JDialog
 */
class DbClientDialogInsert extends JDialog{
    protected JButton ok = new JButton("<html><p>ok", new  ImageIcon(
            FileBeginer.resurse_resurseFolderMenu+Keey.sp + "save.png"));
    private JButton cancel = new JButton(new AbstractAction("<html><p>отмена",
            new ImageIcon(FileBeginer.resurse_resurseFolderMenu+Keey.sp+"cancel.png")){
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
        }
    });
    protected final String tableName;
    protected  List<TableColumn> list = new ArrayList<TableColumn>();
    protected JEditorPane sqlText;

    
    public DbClientDialogInsert(JFrame f, String tableName, JEditorPane _p){
        super(f, true);
        this.tableName = tableName;
        sqlText = _p;
        this.initFrame();
        this.initComponent();
    }

    private void initFrame(){
        setTitle("менеджер БД");
        setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        setResizable(true);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screnSize = kit.getScreenSize();
        int screanHeight = screnSize.height ;
        int screanWidth = screnSize.width ;
        setSize(600, 300);
        setLocation((screanWidth / 2 - 300), (screanHeight / 2 - 150));        
    }

    private void initComponent(){
        String str[][] = this.getDataFromDb();
        if(str == null)
            return;

        TableColumn.helper = new JDialog(this, false);
        for (int i = 0; i < str.length; i++) {
            list.add(new TableColumn(str[i][3], str[i][4] + "("+str[i][5]+")"));
        }
        
        Box b = Box.createHorizontalBox();
        b.add(Box.createHorizontalStrut(2));
        for (int i = 0; i < list.size(); i++) {
            list.get(i).forUpdate.setVisible(false);
            b.add(list.get(i).getPanel());
            b.add(Box.createHorizontalStrut(2));
        }
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(b), BorderLayout.CENTER);

        JLabel l = new JLabel("  таблица : "+tableName+"; схема : "+str[0][1]);
        l.setFont(UserProp.paneFont);
        ok.setFont(UserProp.paneFont);
        cancel.setFont(UserProp.paneFont);
        l.setPreferredSize(new Dimension(l.getPreferredSize().width, 30));
        ok.setMaximumSize(cancel.getPreferredSize());
        cancel.setMaximumSize(cancel.getPreferredSize());
        p.add(l, BorderLayout.NORTH);

        Box b1 = Box.createHorizontalBox();
        b1.add(Box.createGlue());
        b1.add(ok);
        b1.add(Box.createHorizontalStrut(4));
        b1.add(cancel);
        b1.add(Box.createHorizontalStrut(4));

        p.add(b1, BorderLayout.SOUTH);

        this.setContentPane(p);

    }

    private String [][] getDataFromDb(){
        String[][] result = null;
        String[] head = null;
        UserProp up = new UserProp();
        /*String str = "select  TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME," +
                " DATA_TYPE, CHARACTER_MAXIMUM_LENGTH from " + UserProp.dbName +
                ".information_schema.columns where table_name = \'" + tableName + "\';";
        */String str = FileWorker.howInit(
                FileBeginer.resurse_resurseFolder+Keey.sp+FileBeginer.sqlSelects,
                "tableProp").replaceAll("DB_NAME", "" + UserProp.dbName)
                .replaceAll("\'TABLE_NAME\'", "\'" + tableName + "\'");
         sqlText.setText(sqlText.getText() + "\n" + str);
        try {
            DbSelects query = new DbSelects(up.getURL(), up.getUserProp());
            if (query.sendQuery(str)) {
                int rows = query.getRows();
                int cols = query.getColumns();
                result = new String[rows][cols];
                head = new String[cols];
                for (int i = 0; i < head.length; i++) {
                    try {
                        head[i] = "" + query.getMetaData().getColumnName(i + 1);
                    } catch (SQLException exception) {
                    }
                }
                for (int i = 1; i <= rows; i++) {
                    for (int j = 1; j <= cols; j++) {
                        result[i - 1][j - 1] = "" + query.getString(i, j);
                    }
                }
            }
        } catch (Exception ex) {
            if (Keey.debug) {
                System.err.println(ex);
            }
        }

        return result;
    }

    public String getTableSql(){
        StringBuffer tableSql = new StringBuffer();
        tableSql.append("( ");
        for (int i = 0; i < list.size(); i++) {
            if (! list.get(i).getText().equals("")) {
                tableSql.append(" \"" + list.get(i).getColumnName() + "\" ");
                tableSql.append(",");
            }
        }
        return tableSql.toString().substring(0, tableSql.toString().length() - 1) + ")";
    }

    public String getInfoSql() {
        StringBuffer sql = new StringBuffer();
        sql.append("( ");
        for (int i = 0; i < list.size(); i++) {
            if (! list.get(i).getText().equals("")) {
                sql.append(" \'" + list.get(i).getText() + "\' ");
                sql.append(",");
            }
        }

        return sql.toString().substring(0, sql.toString().length() - 1) + ")";
    }

    public String getTableName() {
        return tableName;
    }



    public void okButtonAddAction(ActionListener action){
        ok.addActionListener(action);
    }
}
